package org.example.countDownLatch;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class SemaphoreTest2 {
    public static void main(String[] args) {
       Semaphore semaphore = new Semaphore(10);



        Thread In = new Thread(() -> {
            try {
                semaphore.acquire(); // acquire获得锁
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+"抢到车位");
        });

        Thread Out = new Thread(() -> {
            try {
                semaphore.release(); // acquire获得锁
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+"出车位");
        });


            new Thread(()->{
                for (int i = 1; i <= 20; i++) {
                try {
                        In.start();
                    TimeUnit.SECONDS.sleep(2);
                        Out.start();

                } catch (Exception e) {
                    e.printStackTrace();
                }finally {
                    // 释放锁
                    semaphore.release();
                }
            }
            }).start();

    }
}
